
package com.bh.framework.network;

import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpException;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

public abstract class BaseRequest
{
	private DefaultHttpClient client;

	// private final String RESPONSE_HEADER_NAME_COOKIE = "Set-Cookie";
	private final String REQUEST_HEADER_NAME_COOKIE = "Cookie";

	private String cookie_value = null;

	public BaseRequest()
	{
		HttpParams params = new BasicHttpParams();
		// 设置一些基本参数
		// HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
		// HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
		// HttpProtocolParams.setUseExpectContinue(params, true);
		// HttpProtocolParams.setUserAgent(params,
		// "Mozilla/5.0(Linux;U;Android 2.2.1;en-us;Nexus One Build.FRG83) "
		// +
		// "AppleWebKit/553.1(KHTML,like Gecko) Version/4.0 Mobile Safari/533.1");
		// 超时设置
		/* 从连接池中取连接的超时时间 */
		ConnManagerParams.setTimeout(params, 3900);
		/* 连接超时 */
		HttpConnectionParams.setConnectionTimeout(params, 50000);
		/* 请求超时 */
		HttpConnectionParams.setSoTimeout(params, 120000);

		// 设置我们的HttpClient支持HTTP和HTTPS两种模式
		SchemeRegistry schReg = new SchemeRegistry();
		schReg.register(new Scheme("http", PlainSocketFactory
				.getSocketFactory(), 80));
		schReg.register(new Scheme("https",
				SSLSocketFactory.getSocketFactory(), 443));

		// 使用线程安全的连接管理来创建HttpClient
		ClientConnectionManager conMgr = new ThreadSafeClientConnManager(
				params, schReg);
		client = new DefaultHttpClient(conMgr, params);
	}

	/**
	 * 多参数的get请求 默认
	 * 
	 * @param params
	 * @param url
	 * @return
	 * @throws HttpException
	 * @throws IOException
	 */
	// public String getRequest(List<NameValuePair> params, String url) throws
	// HttpException, IOException{
	// return getRequest(params,url,"");
	// }
	/**
	 * 多参数的get请求 UTF-8
	 * 
	 * @param params
	 * @param url
	 * @return
	 * @throws HttpException
	 * @throws IOException
	 */
	// public String getRequestUTF8(List<NameValuePair> params, String url)
	// throws HttpException, IOException{
	// return getRequest(params,url,"UTF-8");
	// }

	/**
	 * 多参数的get请求 gbk
	 * 
	 * @param params
	 * @param url
	 * @return
	 * @throws HttpException
	 * @throws IOException
	 */
	// public String getRequestGBK(List<NameValuePair> params, String url)
	// throws HttpException, IOException{
	// return getRequest(params,url,"GBK");
	// }

	/**
	 * 多参数的get请求
	 * 
	 * @param params
	 * @param url
	 * @return
	 * @throws HttpException
	 * @throws IOException
	 */
	public String getRequest4Str(String url) throws HttpException, IOException,
			Exception
	{
		String result = null;

		// String strURL;

		// StringBuffer sb = new StringBuffer();
		// if (params != null && params.size() > 0) {
		// for (NameValuePair nvp : params) {
		// String value = URLEncoder.encode(nvp.getValue(), HTTP.UTF_8);
		// if(nvp.getName().equals("oauth_verifier")){
		// value = nvp.getValue();
		// }
		// sb.append(nvp.getName()).append('=').append(value).append('&');
		// }
		// sb.deleteCharAt(sb.length() - 1);
		// }
		// String paramsStr = sb.toString();
		// if (paramsStr != null && !paramsStr.equals("")) {
		// strURL = url + "?" + paramsStr;
		// } else {
		// strURL = url;
		//
		// }
		// Log.e("requestURL="+strURL);

		try
		{
			HttpGet request = new HttpGet(url);

			if (cookie_value != null)
			{
				request.addHeader(REQUEST_HEADER_NAME_COOKIE, cookie_value);
			}

			HttpResponse response = client.execute(request);
			int httpStatusCode = response.getStatusLine().getStatusCode();
			if (httpStatusCode == HttpStatus.SC_OK)
			{
				// if("GBK".equals(entity)){
				// result = EntityUtils.toString(response.getEntity(), "gbk");
				// }else if("UTF-8".equals(entity)){
				result = EntityUtils.toString(response.getEntity(), "UTF-8");
				// }else{
				// result = EntityUtils.toString(response.getEntity());
				// }
			} else
			{
				throw new HttpException("Error Response:"
						+ response.getStatusLine().toString());
			}
		} catch (Exception e)
		{
			// TODO Auto-generated catch block
			// e.printStackTrace();
			throw e;
		}

		return result;
	}

	/**
	 * get请求，无参数，return InputStream
	 * 
	 * @param url
	 * @return
	 * @throws HttpException
	 * @throws IOException
	 */
	public InputStream getRequest(String url) throws HttpException,
			IOException, Exception
	{
		InputStream result;
		try
		{
			result = null;
			HttpGet request = new HttpGet(url);
			if (cookie_value != null)
			{
				request.addHeader(REQUEST_HEADER_NAME_COOKIE, cookie_value);
			}
			HttpResponse response = client.execute(request);
			int httpStatusCode = response.getStatusLine().getStatusCode();
			if (httpStatusCode == 200)
			{
				result = response.getEntity().getContent();
			} else
			{
				throw new HttpException("Error Response:"
						+ response.getStatusLine().toString());
			}
		} catch (Exception e)
		{
			// TODO Auto-generated catch block
			// e.printStackTrace();
			throw e;
		}
		return result;
	}

	/**
	 * 多参数的post请求
	 */
	public String postRequest(List<NameValuePair> params, String url)
			throws HttpException, IOException, Exception
	{
		String result = null;
		try
		{
			HttpPost request = new HttpPost(url);
			if (cookie_value != null)
			{
				request.addHeader(REQUEST_HEADER_NAME_COOKIE, cookie_value);
			}
			if (params != null)
			{
				HttpEntity entity = new UrlEncodedFormEntity(params, HTTP.UTF_8);
				request.setEntity(entity);
			}
			HttpResponse response = client.execute(request);
			int httpStatusCode = response.getStatusLine().getStatusCode();
			if (httpStatusCode == HttpStatus.SC_OK)
			{
				result = EntityUtils.toString(response.getEntity());
				// Log.e("result="+result);
			} else
			{
				throw new HttpException("Error Response:"
						+ response.getStatusLine().toString());
			}
		} catch (Exception e)
		{
			// TODO Auto-generated catch block
			// e.printStackTrace();
			throw e;
		}
		return result;
	}

	/**
	 * 多参数，多文件的post请求
	 * 
	 * @param stringParams
	 * @param fileParams
	 * @param url
	 * @return
	 * @throws HttpException
	 * @throws IOException
	 */
	// public String postRequest(List<NameValuePair> stringParams,
	// List<NameValuePair> fileParams, String url)
	// throws HttpException, IOException {
	// String result = null;
	// HttpPost request = new HttpPost(url);
	// if(cookie_value!=null){
	// request.addHeader(REQUEST_HEADER_NAME_COOKIE, cookie_value);
	// }
	//
	// MultipartEntity entity = new MultipartEntity();
	// for (NameValuePair snv : stringParams) {
	// entity.addPart(snv.getName(), new StringBody(snv.getValue(),
	// Charset.forName("UTF-8")));
	// }
	//
	// for (NameValuePair fnv : fileParams) {
	// File file = new File(fnv.getValue());
	// if (file.isFile() && !file.isDirectory()) {
	// entity.addPart(fnv.getName(), new FileBody(file));
	// }
	// }
	//
	// request.setEntity(entity);
	// HttpResponse response = client.execute(request);
	// int httpStatusCode = response.getStatusLine().getStatusCode();
	// if (httpStatusCode == HttpStatus.SC_OK) {
	// result = EntityUtils.toString(response.getEntity());
	// } else {
	// throw new HttpException("Error Response:" +
	// response.getStatusLine().toString());
	// }
	// return result;
	// }
	public void setCookie(String value)
	{
		cookie_value = value;
	}

	/**
	 * 发送请求
	 * 
	 * @param path
	 *            请求路径
	 * @param params
	 *            请求参数 key为参数名称 value为参数值
	 * @param encode
	 *            请求参数的编码UTF-8
	 * @return
	 * @throws IOException
	 * 
	 */
	public String postFormData(String path, List<NameValuePair> params)
			throws IOException, Exception
	{
		InputStream mInputStream = post(path, params);
		byte bytes[] = readStream(mInputStream);
		String result = new String(bytes);
		return result;
	}

	/**
	 * 获取GB2312格式数据
	 * 
	 * @param context
	 * @param path
	 * @param params
	 * @return
	 * @throws Exception
	 */
	// public String postFormDataGB2312(String path,List<NameValuePair> params)
	// throws IOException{
	// InputStream mInputStream = post(path, params);
	// byte bytes[] = readStream(mInputStream);
	// String result = new String(bytes, "GB2312");
	// return result;
	// }

	/**
	 * 读取流
	 * 
	 * @param inStream
	 * @return 字节数组
	 * @throws IOException
	 * @throws Exception
	 */
	public byte[] readStream(InputStream inStream) throws IOException
	{
		ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
		byte[] buffer = new byte[10240];
		int len = -1;
		while ((len = inStream.read(buffer)) != -1)
		{
			outSteam.write(buffer, 0, len);
		}
		outSteam.close();
		inStream.close();
		return outSteam.toByteArray();
	}

	/**
	 * 发送请求这里面把发送数据与接收数据保存下来
	 * 
	 * @param context
	 * @param path
	 *            请求路径
	 * @param params
	 *            请求参数 key为参数名称 value为参数值
	 * @param encode
	 *            请求参数的编码
	 * @throws IOException
	 */
	private InputStream post(String path, List<NameValuePair> params)
			throws IOException, Exception
	{
		try
		{
			StringBuilder parambuilder = new StringBuilder("");
			if (params != null && params.size() > 0)
			{
				for (NameValuePair nvp : params)
				{
					String value = null;
					try
					{
						value = URLEncoder.encode(nvp.getValue(), HTTP.UTF_8);
					} catch (UnsupportedEncodingException e)
					{
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					if (nvp.getName().equals("oauth_verifier"))
					{
						value = nvp.getValue();
					}
					parambuilder.append(nvp.getName()).append('=')
							.append(value).append('&');
				}
				parambuilder.deleteCharAt(parambuilder.length() - 1);
			}
			byte[] data = parambuilder.toString().getBytes();

			URL url = new URL(path);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setDoOutput(true);// 允许对外发送请求参数
			conn.setUseCaches(false);// 不进行缓存
			conn.setConnectTimeout(5 * 1000);
			conn.setRequestMethod("POST");
			// 下面设置http请求头
			conn.setRequestProperty(
					"Accept",
					"image/gif, image/jpeg, image/pjpeg, image/pjpeg, application/x-shockwave-flash, application/xaml+xml, application/vnd.ms-xpsdocument, application/x-ms-xbap, application/x-ms-application, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*");
			conn.setRequestProperty("Accept-Language", "zh-CN");
			conn.setRequestProperty(
					"User-Agent",
					"Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.2; Trident/4.0; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.04506.30; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)");
			conn.setRequestProperty(
					"Content-Type", "application/x-www-form-urlencoded");
			conn.setRequestProperty(
					"Content-Length", String.valueOf(data.length));
			conn.setRequestProperty("Connection", "Keep-Alive");

			// 发送参数
			DataOutputStream outStream = new DataOutputStream(
					conn.getOutputStream());
			outStream.write(data);// 把参数发送出去
			outStream.flush();
			outStream.close();
			if (conn.getResponseCode() == 200)
			{
				// 访问正常用就把数据保下来
				// int contenlength = conn.getContentLength()/4;
				// if(context instanceof ThreeGVolumeListner){
				// ThreeGVolumeListner listener=(ThreeGVolumeListner) context;
				// listener.sendInformMessageDeal();}
				// if (NetWorkInfo.isIswifi()) {
				// SettingSharePreference.updateWIFI(context, contenlength);
				// } else {
				// SettingSharePreference.updateGPRS(context, contenlength);
				// }
				return conn.getInputStream();
			}
		} catch (Exception e)
		{
			// TODO Auto-generated catch block
			// e.printStackTrace();
			throw e;
		}
		return null;
	}
}
